//
//  HNConcernViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/16.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNConcernViewController.h"
#import "HNDoctorDetailViewController.h"

@interface HNConcernViewController ()

@property (nonatomic,assign)CGFloat contentHeight;

@property (nonatomic,strong)NSMutableArray *goodsDataSource;

@property (nonatomic,assign)NSInteger goodsDataCount;

@property (nonatomic,strong)UIButton *deleteBtn;


@property (nonatomic,strong) UIView *shoppingView;

@end

@implementation HNConcernViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.goodsDataSource = [[NSMutableArray alloc]init];
    
    [self drawView];
    [self initData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)drawView{
    //添加点击按钮---添加一个按钮
    UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [clickBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [clickBtn setFont:[UIFont systemFontOfSize:15]];
    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateNormal];
    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateSelected];
    
    clickBtn.frame = CGRectMake(0,0,40,20);
    [clickBtn addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clickBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    
    _contentHeight = 0;
    _contentScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height - 70)];
     _contentScrollView.backgroundColor = RGB(236, 240, 241);
    _contentScrollView.bounces = YES;
    [self.view addSubview:_contentScrollView];
    
    
    _shoppingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    _shoppingView.backgroundColor = RGB(236, 240, 241);
    
    [_contentScrollView addSubview:_shoppingView];
//    [self setDoctorList];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
}

-(void)initData{
    [self getDoctorData];
}


#pragma mark - 设置列表
-(void)setDoctorList{
    CGFloat bl = 6;//border边距
    CGFloat gl = 4;//gap间隙
    
    NSInteger num = self.goodsDataSource.count;
    //当商品列表为空时
    if (num == 0) {
        [self showHint:@"暂无关注"];
    }
    
    for (NSInteger i = 0; i < self.goodsDataSource.count; i++) {
        NSDictionary *goodsDataDic  = self.goodsDataSource[i];
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake((kScreen_Width/2 - bl/2) * !(i%2 == 0) + bl, _contentHeight, kScreen_Width/2, 0)];
        [self.shoppingView addSubview:itemView];
        //商品图
        UIImageView *goodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, gl * 2, kScreen_Width/2 - bl*3/2, kScreen_Width/2 - bl*3/2)];
        
        NSString *goodsImageStr = [NSString stringWithFormat:@"%@%@",url_Base,[goodsDataDic objectForKey:@"photo"]];
        [goodsImageView sd_setImageWithURL:[NSURL URLWithString:goodsImageStr] placeholderImage:[UIImage imageNamed:@"D99GN4P63Q4F@2x.png"]];
        
        goodsImageView.layer.masksToBounds = YES;
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:goodsImageView.bounds  byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        goodsImageView.layer.mask = maskLayer;
        
        [itemView addSubview:goodsImageView];
        
        
        
        //商品名
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, goodsImageView.frame.origin.y + goodsImageView.frame.size.height, goodsImageView.frame.size.width, 18 + gl)];
        nameLabel.numberOfLines = 1;
        nameLabel.backgroundColor = [UIColor whiteColor];
        nameLabel.font = [UIFont systemFontOfSize:15];
        nameLabel.textColor = RGBJ(165);
        NSString *realName = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"realName"]];
        NSString *nickname = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"nickname"]];
        NSString *username = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"username"]];
        if ([AppConfig isNULL:nickname]) {
            if ([AppConfig isNULL:realName]){
                nameLabel.text = username;
            }else{
                nameLabel.text = realName;
            }
        }else {
            nameLabel.text = nickname;
        }
        [itemView addSubview:nameLabel];
        //商品描述
        UILabel *detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, nameLabel.frame.origin.y + nameLabel.frame.size.height, goodsImageView.frame.size.width, 15 + gl)];
        detailLabel.backgroundColor = [UIColor whiteColor];
        detailLabel.numberOfLines = 1;
        detailLabel.font = [UIFont systemFontOfSize:11];
        detailLabel.textColor = RGB(112, 112, 112);
        
        detailLabel.text = [NSString stringWithFormat:@" %@",[goodsDataDic objectForKey:@"flag1"]];
        [itemView addSubview:detailLabel];
        
        
        UIView *gapView = [[UIView alloc]initWithFrame:CGRectMake(0, detailLabel.frame.origin.y + detailLabel.frame.size.height, goodsImageView.frame.size.width, 10)];
        
        gapView.layer.masksToBounds = YES;
        
        CAShapeLayer *gapViewLayer = [CAShapeLayer layer];
        gapViewLayer.path = [UIBezierPath bezierPathWithRoundedRect:detailLabel.bounds  byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        detailLabel.layer.mask = gapViewLayer;
        
        [itemView addSubview:detailLabel];
        
        //添加进入详情页的点击按钮
        UIButton *clickBtn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn1 setTitle:@"" forState:UIControlStateNormal];
        [clickBtn1 setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn1.tag = i + 10000;
        clickBtn1.frame = goodsImageView.frame;
        [clickBtn1 addTarget:self action:@selector(enterDoctorDetail:) forControlEvents:UIControlEventTouchUpInside];
        [itemView addSubview:clickBtn1];
        
        //添加删除关注的点击按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.deleteBtn = clickBtn;
        [self.deleteBtn setHidden:YES];
        [clickBtn setFont:[UIFont systemFontOfSize:15]];
        [clickBtn setBackgroundImage:[UIImage imageNamed:@"椭圆-1.png"] forState:UIControlStateNormal];
        [clickBtn setBackgroundImage:[UIImage imageNamed:@"552cc35c851ca_128.png"] forState:UIControlStateSelected];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.tag = 20000 + i;
        clickBtn.frame = CGRectMake(goodsImageView.frame.size.width - 35,15,25,25);
        clickBtn.layer.masksToBounds = YES;
        clickBtn.layer.cornerRadius = clickBtn.frame.size.width/2;
        clickBtn.backgroundColor = [UIColor whiteColor];
        [clickBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        [itemView addSubview:clickBtn];
        
        //设置列表高度
        CGRect itemViewFrame = itemView.frame;
        itemViewFrame.size.height = goodsImageView.frame.size.height + detailLabel.frame.size.height + nameLabel.frame.size.height + gapView.frame.size.height ;
        itemView.frame = itemViewFrame;
        if (i%2 == 1 || (i + 1 == num && num%2 == 1)) {
            //设置列表高度
            _contentHeight = _contentHeight + itemView.frame.size.height;
            //最后一行加载后再改变scrollView高度
            if(i + 1 == num){
                _contentScrollView.contentSize = CGSizeMake(kScreen_Width, _contentHeight);
            }
            //设置商品高度
            CGRect shoppingViewFrame = self.shoppingView.frame;
            shoppingViewFrame.size.height = shoppingViewFrame.size.height + itemView.frame.size.height;
            self.shoppingView.frame = shoppingViewFrame;
        }
    }
    
    
    self.goodsDataCount = self.goodsDataSource.count;
    
}

#pragma -mark 编辑
-(void)editAction:(UIButton *)btn{
    if (btn.selected) {
        for (NSInteger i = 20000; i < 20011; i ++ ) {
            UIButton *myButton = (UIButton *)[self.view viewWithTag:(i)];
            [myButton setHidden:YES];
        }
        [btn setTitle:@"编辑" forState:UIControlStateNormal];
          [self cancelDoctorConcern];
    }else{
        for (NSInteger i = 20000; i < 20011; i ++ ) {
             UIButton *myButton = (UIButton *)[self.view viewWithTag:(i)];
            [myButton setHidden:NO];
        }
        
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        
      
    }
    btn.selected = !btn.selected;
}


#pragma -mark 删除
-(void)deleteAction:(UIButton *)btn{
//    NSInteger tag = btn.tag - 20000;
    btn.selected = !btn.selected;
}

#pragma mark - 取消医生关注
-(void)cancelDoctorConcern{
    NSString *allUserIdStr = [[NSString alloc]init];
    for (int i = 0; i<_goodsDataSource.count; i++) {
         UIButton *myButton = (UIButton *)[self.shoppingView viewWithTag:(i+20000)];
        if (myButton.selected) {
            NSDictionary *doctorDic = _goodsDataSource[i];
            NSString *userId = [NSString stringWithFormat:@"%@",[doctorDic objectForKey:@"targetUserId"]];
            if (allUserIdStr.length == 0) {
                allUserIdStr = [userId copy];
            }else{
                allUserIdStr = [allUserIdStr stringByAppendingString:[NSString stringWithFormat:@",%@",userId]];
            }
        }
    }
    NSLog(@"%@",allUserIdStr);
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    [param setObject:allUserIdStr forKey:@"targetUserId"];
    NSLog(@"param = %@",param);
    
    
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_collect_delete parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"取消关注失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            
            [self getDoctorData];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"取消关注失败"];
    }];

    
    
}


#pragma -mark 进入医生详情页
-(void)enterDoctorDetail:(UIButton *)btn{
    NSInteger tag = btn.tag - 10000;
    NSDictionary *goodsDataDic  = self.goodsDataSource[tag];
    NSLog(@"%@",goodsDataDic);
    
    HNDoctorDetailViewController *doctorDetailVC = [[HNDoctorDetailViewController alloc]init];
    doctorDetailVC.title = @"医生详情";
     doctorDetailVC.userId = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"targetUserId"]];
    
    
    [self.navigationController pushViewController:doctorDetailVC animated:YES];
}


-(void)getDoctorData{
    
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
//    [param setObject:[NSString stringWithFormat:@"%d",_cur] forKey:@"cur"];
    NSLog(@"param = %@",param);
    
    
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_collect_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取关注医生列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSMutableArray* obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            [_goodsDataSource removeAllObjects];
            for (int i = 0; i < obj.count; i ++) {
                NSLog(@"%@",obj[i]);
                [self.goodsDataSource addObject:obj[i]];
            }
            
            NSLog(@"===self.docterListSource = %@",self.goodsDataSource);
            
             _contentHeight = 0;
            [_shoppingView removeFromSuperview];
            _shoppingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
            _shoppingView.backgroundColor = RGB(236, 240, 241);
            [_contentScrollView addSubview:_shoppingView];
    
            
            [self setDoctorList];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取关注医生列表失败"];
    }];
    
}



@end
